package org.plumecache.springboot.autoconfigurer;

import com.google.gson.Gson;
import com.plumecache.core.CacheService;
import com.plumecache.core.CacheServiceFactory;
import com.plumecache.core.StatisticsService;
import com.plumecache.core.common.StatisticsDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/plumecache")
@ConditionalOnWebApplication
public class PlumecacheController {

    private final Gson gson = new Gson();
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StatisticsService statisticsService;

    @GetMapping("list")
    public ResponseEntity<List<StatisticsDTO>> list() {
        return ResponseEntity.ok(statisticsService.getStatisticsDTOList());
    }

    @RequestMapping("execute")
    public String execute(@RequestBody CacheCommand cacheCommand) {
        if (log.isDebugEnabled()) {
            log.debug("execute command,{}", gson.toJson(cacheCommand));
        }

        String instanceName = cacheCommand.getInstanceName();

        if (StringUtils.isEmpty(instanceName)) {
            instanceName = CacheServiceFactory.getInstance().getProperties().getName();
        }

        CacheService cacheService = CacheServiceFactory.getInstance(instanceName);
        if (cacheService == null) {
            return String.format("cache instance %s no find", instanceName);
        }

        cacheCommand.setCacheInstance(cacheService);

        try {
            return cacheCommand.execute();
        } catch (Exception e) {
            log.error("command execute error,command:{},ex:{}", gson.toJson(cacheCommand), ExceptionUtils.getStackTrace(e));
            return String.format("command execute error:%s", ExceptionUtils.getStackTrace(e));
        }
    }

}
